package com.wh.wisdomsite.xbox.server.controller.st;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.st.ProductIn;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.session.ServerSessionUser;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.st.entity.Product;
import com.wh.wisdomsite.xbox.st.service.IProductService;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * 产品信息控制层
 *
 * @author 蔡道行
 * @version V1.0
 * @package com.wh.wisdomsite.xbox.server.controller.st
 * @date 15:11 2018/12/24
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2014
 */
@Controller
@RequestMapping(value = "/product")
public class ProductController {

    private static final Log logger = LogFactory.getLog(ProductController.class);

    @Autowired
    private IProductService iProductService;


    /**
     * 跳转到产品页面
     *
     * @return
     */
    @RequiresPermissions("rules:st_product_page")
    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(HttpServletRequest request) {
        Integer companyId = UserUtils.getCurrentUser().getCompanyId();
        request.setAttribute("DefaultCompany", companyId);
        return "st/product/productList";
    }

    /**
     * 获取产品列表
     *
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:st_product_find")
    @RequestMapping(value = "/productList.do")
    public void productList(HttpServletResponse response,  ProductIn in) {
        try {
            logger.info("加载产品列表-->>开始");
            logger.info("加载产品列表-->>开始-->>" + in.getPage());
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<Product> page = new Page<Product>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<Product> ewproduct = new EntityWrapper<Product>();
            ewproduct.setEntity(new Product());
            Boolean isAdmin = UserUtils.isSysAdmin();
            //若不是管理员则添加查询条件
            if (!isAdmin) {
                ewproduct = setEntityWrapper(ewproduct, "co");
            }
            if (StringUtils.isNotEmpty(in.getSupId())) {
                ewproduct.eq(" s.supId", in.getSupId());
            }
            if (StringUtils.isNotEmpty(in.getMaterialName())) {
                ewproduct.like("P.materialName", in.getMaterialName());
            }
            ewproduct.orderBy("P.createDate", true);
            Page<Map<String, Object>> productPage = iProductService.getMapsPage(page, ewproduct);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (productPage.getRecords().size() > 0) {
                for (Map<String, Object> product : productPage.getRecords()) {
                    JSONObject object = new JSONObject(product);
                    if (product.get("supplier") != null) {
                        object.put("supplier", new JSONObject(product.get("supplier")));
                    }
                    array.put(object);
                }
            }
            json.put("total", productPage.getTotal());
            json.put("rows", array);
            ResManager.getTextOut(response).print(json);
            logger.info("加载产品列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 产品详情
     *
     * @param productIn
     * @param request
     * @return
     */
    @RequiresPermissions("rules:st_product_view")
    @RequestMapping("productDesc.do")
    public String productDescDetails(ProductIn productIn, HttpServletRequest request) {
        logger.info("产品详情-->>开始");
        try {
            Map<String, Object> product = iProductService.getMapById(productIn.getProId());
            if (null != product.get("createBy")) {
                product.put("createBy", UserMapManager.getUserLoginNameInMap(product.get("createBy").toString()));
            }
            if (null != product.get("updateBy")) {
                product.put("updateBy", UserMapManager.getUserLoginNameInMap(product.get("updateBy").toString()));
            }
            request.setAttribute("product", product);
            logger.info("产品详情-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "st/product/productDesc";
    }

    /**
     * 删除产品
     *
     * @param proId
     * @param response
     */
    @RequiresPermissions("rules:st_product_del")
    @RequestMapping(value = "del.do", method = RequestMethod.GET)
    public void del(String proId, HttpServletResponse response) {
        try {
            logger.info("删除产品-->>开始");
            iProductService.deleteById(proId);
            logger.info("删除产品-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("删除成功"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除产品-->>Exception" + e.getMessage());
        }
    }


    /**
     * 跳转至添加或修改页面
     *
     * @return
     */
    @RequestMapping("/toProduct.do")
    public ModelAndView toAddProduct(String proId, HttpServletRequest request) {
        logger.info("添加修改产品跳转-->>开始");
        Map<String, Object> product = null;
        if (StringUtils.isNotEmpty(proId)) {
            product = iProductService.getMapById(proId);
            request.setAttribute("product", product);
        }
        Integer companyId = UserUtils.getCurrentUser().getCompanyId();
        request.setAttribute("DefaultCompany", companyId);
        logger.info("添加修改产品跳转-->>开始");
        return new ModelAndView("st/product/productOption");
    }

    /**
     * 更新或修改产品
     *
     * @param product
     * @param response
     */
    @RequiresPermissions("rules:st_product_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(Product product, HttpServletResponse response) {
        //查看产品是否已经存在
        try {
            if (StringUtils.isNotEmpty(product.getProId())) {
                logger.info("修改产品-->>开始");
                product.setUpdateDate(new Date());
                product.setUpdateBy(UserUtils.getCurrentUser().getUsId());
                iProductService.updateById(product);
                System.out.println("完毕");
                logger.info("修改产品-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("更新产品成功"));
            } else {
                logger.info("添加产品-->>开始");
                product.setCreateBy(UserUtils.getCurrentUser().getUsId());
                product.setCreateDate(new Date());
                iProductService.insert(product);
                logger.info("添加产品-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("添加产品成功"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加修改产品-->>Exception" + e.getMessage());
        }
    }


    /**
     * 根据权限设置查询范围
     *
     * @param ew
     * @param companyTableAlias
     * @return
     */
    public EntityWrapper setEntityWrapper(EntityWrapper ew, String companyTableAlias) {
        ServerSessionUser serverSessionUser = UserUtils.getServerSessionUser();
        String dataScope = serverSessionUser.getDataScope();
        //设置一个查询用的代码
        String codeForFind = null;
        switch (dataScope) {
            case "1":
                codeForFind = serverSessionUser.getFinalCompCode();
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)) {
                    ew.like(companyTableAlias + ".compCode", codeForFind);
                }
                break;
            case "2":
                codeForFind = serverSessionUser.getFinalCompCode();
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)) {
                    ew.eq(companyTableAlias + ".compCode", codeForFind);
                }
                break;
            default:
                break;
        }
        return ew;
    }


}
